var express = require('express');
var router = express.Router();
var axios = require('axios');
var fs = require('fs');
const FormData = require('form-data');

// 请替换为您的有效API密钥
var AK = 'EQ6NXVk0V5u01eOcdIOz9NB2'; // 替换为您的API Key
var SK = 'Uy2lA03EsrBoDfQUngz9MmQFVh1A3RWp'; // 替换为您的Secret Key

router.post('/TextRecognition', async (req, res) => {
    let { image } = req.body;
    
    try {
        // 检查图片数据是否存在
        if (!image) {
            return res.status(400).json({
                code: 400,
                message: '缺少图片数据'
            });
        }

        // 处理图片数据
        let imageData;
        if (image.startsWith('data:image')) {
            // 如果是base64格式的图片，提取base64部分
            imageData = image.split(',')[1];
        } else {
            imageData = image;
        }

        // 获取access_token
        const accessToken = await getAccessToken();
        
        // 准备请求参数
        const formData = new URLSearchParams();
        formData.append('image', imageData);
        formData.append('detect_direction', 'false');
        formData.append('vertexes_location', 'false');
        formData.append('paragraph', 'false');
        formData.append('probability', 'false');

        // 调用百度OCR API
        const response = await axios({
            method: 'POST',
            url: `https://aip.baidubce.com/rest/2.0/ocr/v1/accurate?access_token=${accessToken}`,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Accept': 'application/json'
            },
            data: formData,
            timeout: 30000
        });

        // 处理响应
        if (response.data.error_code) {
            return res.json({
                code: 400,
                message: `百度OCR识别失败: ${response.data.error_msg}`
            });
        }

        // 提取识别结果
        const words = response.data.words_result || [];
        const text = words.map(item => item.words).join('');

        return res.json({
            code: 200,
            message: '识别成功',
            data: text
        });

    } catch (error) {
        console.error('文字识别错误:', error);
        return res.status(500).json({
            code: 500,
            message: '文字识别失败: ' + error.message
        });
    }
});

function getAccessToken() {
    return new Promise((resolve, reject) => {
        const options = {
            method: 'POST',
            url: `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${AK}&client_secret=${SK}`,
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        };

        axios(options)
            .then(res => {
                if (res.data && res.data.access_token) {
                    resolve(res.data.access_token);
                } else {
                    reject(new Error('无法获取访问令牌'));
                }
            })
            .catch(error => {
                reject(error);
            });
    });
}

module.exports = router;

